<template>
  <el-dialog
      title="发表文章"
      v-model="dialogVisible"
      width="100%"
      fullscreen
      @open="open"
      @close="closeDialog"
      :before-close="handleClose"
  >
    <el-form :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm" v-loading="loading" ref="addForm">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="ruleForm.title" style="width: 250px"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id" class="select">
        <el-select v-model="ruleForm.cate_id" placeholder="请选择分类"  class="selectItem" style="width: 250px">
          <el-option v-for="item in articleListCategory" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章内容" prop="context">
        <MyEditor ref="Editor"/>
      </el-form-item>
      <el-form-item label="封面图片" class="uploadImg" prop="img">
        <img
            :src="baseImg"
            alt=""
            class="cover-img"
            ref="imgRef"
            style="width: 400px; height: 300px"
        />
        <br />
        <!-- 文件选择框，默认被隐藏 -->
        <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFileRef"
            @change="onCoverChangeFn"
        />

      </el-form-item>
      <el-form-item>
        <!-- 选择封面的按钮 -->
        <el-button link type="primary" @click="chooseImgFn">+ 选择封面</el-button>
      </el-form-item>
      <div class="uploadArticleBtn">
        <el-button type="primary" class="btnToSendServer" v-onceClick="10000" @click="uploadArticleToServer('已发布')" style="margin-left: 200px;">发布</el-button>
        <el-button type="info"    class="btnToSendServer" v-onceClick="10000" @click="uploadArticleToServer('草稿')">存为草稿</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import {reactive, ref, watch} from "vue";
import {addArticle, getArticleClassification} from "@/api";
import MyEditor from '@/components/MyEditor'
import img from '@/assets/img/cover.jpg'
import {ElMessage} from "element-plus";
export default {
  name: "UIndex",
  props:['isShowAddArticle'],
  components:{MyEditor},
  setup(props, context){
    /*
    * 状态
    * */

    // dialog开关
    let dialogVisible = ref(false)

    // 表单
    let ruleForm =  reactive({
      title: '',
      cate_id: '',
      content: '<h1>请输入文本</h1>',
      cover_img: '',
      state: ''
    })

    // 表单规则
    let rules = reactive({
      title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
      ],
      cate_id: [
        { required: true, message: '请选择文章分类', trigger: 'blur' }
      ]
    })

    // 文章分类
    let articleListCategory = reactive([])

    // loading状态
    let loading = ref(true)

    // 拿到editor的ref
    let Editor = ref(null)

    let baseImg = ref(img)

    let imgRef = ref(null)

    let iptFileRef = ref(null)

    let addForm = ref()
    /*
    * 方法
    * */
    // 获取文章分类
    const getArticleClassificationList = async () => {
      articleListCategory.length = 0
      const res = await getArticleClassification()
      articleListCategory.push(...res.data)
    }

    // dialog打开的回调
    const open = async () => {
      await getArticleClassificationList()
      loading.value = false
    }

    // dialog关闭的回调
    const handleClose = () => {
      clear()
      addForm.value.resetFields()
      context.emit('ArticleList')
      context.emit('closeAddArticleDialog')
    }

    // 发布文章
    const uploadArticleToServer = async (state) => {
      ruleForm.state = state
      ruleForm.content = Editor.value.valueHtml
      const fd = new FormData()
      // 向 FormData 中追加数据
      Object.keys(ruleForm).forEach((key) => {
        fd.append(key, ruleForm[key])
      })
      const res = await addArticle(fd)
      ElMessage.success(res.message)
      handleClose()
    }

    // 获取图片
    const onCoverChangeFn = (e) => {
      // 获取用户选择的文件列表
      const files = e.target.files
      if (files.length === 0) {
        // 用户没有选择封面
        ruleForm.cover_img = null
        imgRef.value.setAttribute('src', baseImg)
      } else {
        // 用户选择了封面
        ruleForm.cover_img = files[0]
        const url = URL.createObjectURL(files[0])
        imgRef.value.setAttribute('src', url)
      }
    }

    //点击获取图片按钮
    const chooseImgFn = () => {
      iptFileRef.value.click()
    }


    const clear = () => {
      ruleForm.state = ''
      ruleForm.cate_id = ''
      ruleForm.title = ''
      ruleForm.content = ''
      Editor.value.valueHtml = '<p>请输入内容</p>'
      ruleForm.cover_img = ''
      imgRef.value.setAttribute('src', img)
    }

    /*
    * watch和computed
    * */
    watch(() => props.isShowAddArticle, (a) => {
      dialogVisible.value = a
    })

    return{
      ruleForm,
      rules,
      articleListCategory,
      loading,
      dialogVisible,
      Editor,
      baseImg,
      imgRef,
      iptFileRef,
      addForm,
      onCoverChangeFn,
      open,
      getArticleClassificationList,
      handleClose,
      uploadArticleToServer,
      chooseImgFn,
      clear
    }
  }
}
</script>

<style scoped>
.uploadArticleBtn{
  width: 100%;
}
.el-button{

}
</style>
